#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <ctype.h>
#include <dirent.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>

#include "gm_file.h"
#include "func.h"

int startsWith(const char *str, const char *prefix) 
{
	size_t prefix_len = strlen(prefix);
	return strncmp(str, prefix, prefix_len) == 0;
}

int exist_file(const char* fn)
{
	struct stat s;
	if (stat(fn, &s) == 0) {
		if (S_ISREG(s.st_mode)) {
			return 0;
		}
	}
	return 1;
}


#define COST(U) (U == 'G' ? 1024*1024*1024 : U == 'M' ? 1024*1024 : U == 'K' ? 1024 : 1)
uint64_t __to_unit(uint64_t size, char* unit)
{
	char _unit[9] = {'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
	uint64_t count = 0;
	uint64_t _size = 0;

	while (size > 1024 && count < 9) {
		size = size >> 10;
		count ++;
	}

	*unit = _unit[count];
	_size = size;

	return _size;
}

void get_process_rss(float* VmSize, float* VmRSS)
{
	FILE* fp;
	char *p;
	char line[512];
	float vmsize = 0, vmrss = 0;
	char unit;

	do {
		fp = fopen("/proc/self/status", "r");
		if (fp == NULL) {
			fprintf(stderr, "fopen returned 0\n");
			break;
		}
		while (fgets(line, 511, fp) != NULL) {
			p = skip_whitespace(line);
			if (startsWith(p, "VmSize")) {
				p = strpbrk(p, "1234567890");
				vmsize = atoi(p);
				p = strpbrk(p, "KkMmGgBb");
				unit = toupper(*p);
				vmsize = vmsize * COST(unit) / COST('M');
			} else if (startsWith(p, "VmRSS")) {
				p = strpbrk(p, "1234567890");
				vmrss = atoi(p);
				p = strpbrk(p, "KkMmGgBb");
				unit = toupper(*p);
				vmrss = vmrss * COST(unit) / COST('M');
				break;
			}
		}
		fclose(fp);
		if (VmSize) *VmSize = vmsize;
		if (VmRSS) *VmRSS = vmrss;
	} while (0);
}

